import { NavLink } from 'react-router-dom';
import { Menu, Icon } from 'antd';
import { connect } from 'react-redux';
import { switchMenu, setUserAuth } from '@/redux/action/index';
import less from './index.less';
import logo from './demo.png';

const SubMenu = Menu.SubMenu;

class LeftNav extends React.Component {
    state = {
        menuTreeNode: '',
        currentKey: ['home'],
        defaultOpenKeys: []
    }

    _isMounted = false //该组件是否被挂载，用于取消ajax请求的执行

    componentWillMount() {
        this._isMounted = true;
        const currentKey = window.location.hash.replace(/#|\?.*$/g, '');
        let defaultOpenKeys = currentKey.split('/');
        defaultOpenKeys = '/' + defaultOpenKeys[1];

        // 
        const { dispatch } = this.props;
        dispatch(setUserAuth());

        this.setState({
            currentKey: [currentKey],
            defaultOpenKeys: [defaultOpenKeys]
        });
    }

    componentWillUnmount() {
        this._isMounted = false
    }

    handelClickMenu = ({ item, key }) => {
        if (key == this.state.currentKey) {
            return false;
        }
        // 事件派发，自动调用reducer，通过reducer保存到store对象中
        const { dispatch } = this.props;
        dispatch(switchMenu(item.props.eventKey));
        this.setState({
            currentKey: [key]
        });
    }

    // 菜单渲染
    renderMenu = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <SubMenu title={item.title} key={item.path}>
                        {this.renderMenu(item.children)}
                    </SubMenu>
                )
            }
            return <Menu.Item title={item.title} key={item.path}>
                <NavLink to={item.path}>{item.title}</NavLink>
            </Menu.Item>
        });
    }

    render() {
        const menuList=this.renderMenu(this.props.menuList);
        return (
            <div className={less.main_leftNav}>
                <div className={less.main_leftNav_logo}>
                    <img src={logo} alt="" />
                </div>
                <Menu
                    className={less.main_leftNav_menu}
                    defaultOpenKeys={this.state.defaultOpenKeys}
                    selectedKeys={this.state.currentKey}
                    theme="dark"
                    mode="inline"
                    onClick={this.handelClickMenu}
                >
                    {menuList}
                </Menu>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        menuList: state.menuList
    }
}

export default connect(mapStateToProps)(LeftNav)
